package com.zhang.modules.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zhang.common.jpa.entity.DTO;
import com.zhang.common.jpa.service.impl.BaseServiceImpl;
import com.zhang.exception.exception.NormalException;
import com.zhang.modules.auth.eneity.Permission;
import com.zhang.modules.auth.eneity.Role;
import com.zhang.modules.auth.eneity.cmd.AddRoleDto;
import com.zhang.modules.auth.eneity.dto.RoleDto;
import com.zhang.modules.auth.rep.RoleRep;
import com.zhang.modules.auth.service.IPermissionService;
import com.zhang.modules.auth.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;


@Service
public class RoleService extends BaseServiceImpl<RoleRep, Role,String> implements IRoleService {

    private IPermissionService permissionService;

    public RoleService(IPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public int deleteByIdNotIn(Set<String> ids) {
        return getRep().deleteByIdNotIn(ids);
    }

    @Override
    public Role add(AddRoleDto roleDto) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDto,role);

        //设置权限
        Set<Permission> pervList = permissionService.getByIdsLogic(roleDto.getIds());
        role.setPermissions(pervList);
        return save(role);
    }

    @Override
    public boolean edit(AddRoleDto role) {
        //查询数据库
        Role DBRole = get(role.getId());
        if (DBRole == null) throw new NormalException("角色不存在");
        //copy修改值
        BeanUtils.copyProperties(role,DBRole);
        //重置角色权限关系表
        getRep().resetRole(role.getId());
        DBRole.setPermissions(permissionService.getByIdsLogic(role.getIds()));
        //更新
        return update(DBRole);
    }


    @Override
    public <R extends DTO> R convert2DtoSingle(Role orginInfo) {
        RoleDto roleDto = new RoleDto();
        BeanUtils.copyProperties(orginInfo,roleDto);
        return (R) roleDto;
    }
}
